<?php
// .-----------------------------------------------------------------------------------
// | WE TRY THE BEST WAY 杭州博也网络科技有限公司
// |-----------------------------------------------------------------------------------
// | Author: 吃草的鱼 <783188184@qq.com>
// | Copyright (c) 2013-2016, http://www.itboye.com. All Rights Reserved.
// |-----------------------------------------------------------------------------------

namespace Home\Controller;
use Shop\Api\GrouporderidApi;
use Think\Controller;
use Shop\Api\CategoryApi;
use Common\Api\WeixinApi;
use Shop\Api\ProductApi;
use Shop\Api\ProductSkuApi;
use Shop\Api\ProductGroupApi;
use Shop\Api\ProductImageApi;
use Weixin\Api\WxuserApi;
use Admin\Api\UserPictureApi;
use Shop\Api\AddressApi;
use Shop\Api\OrdersApi;
use Shop\Api\OrdersItemApi;
use Shop\Api\OrdersContactInfoApi;
use Shop\Api\GroupattendApi;
use Shop\Api\GroupApi;
use Shop\Api\GroupOrderApi;
use Shop\Api\OrdersExpressApi;
use Shop\Api\BannersApi;
use Weixin\Controller\Weixinjs;
use Home\Controller\JssdkController;

class GroupController extends HomeController {

    /*
	 * 首页 分为两种情况需要异步加载
	 *
	 * */
    public function index() {
        //调出发布的商品
        $page['curpage'] = I('curpage') ? I('curpage') : 1;//默然首页第一页
        $page['size']    = 20;

        //这里的商品一般都是一件当这一被下单时设置商品的status为0 在支付成功后再设置sku中的数量为零
        //搜索查询
        $maplike = I('name');
        if (!empty($maplike)) {
            $map['name'] = array('like', '%' . $maplike . '%');
            $this->assign('name', $maplike);//用于分页条件筛选
        }
        $map['cate_id'] = array('in', '23,26');
        $map['status']=1;$map['onshelf']=1;
        //分页数据可能会大于有的记录数所以在里面做了处理防止报错,去除商品详情
        $res = apiCall(ProductApi::PAGE_ALL_PRODUCT, array($map, $page, 'createtime desc', 'id,cate_id'));
        //下面这一块主要是取出主要图像组装
        if ($res['status'] && !is_null($res['info'])) {
            $productidarr = array_column($res['info'], 'id');
            $productidstr = implode(',', $productidarr);
            $pimap['id']  = array('in', $productidstr);
            $group=true;$pimap['type']=6015;
            $res          = apiCall(ProductApi::ALLQUERY, array(
                $pimap,
                array('curpage' => $page['curpage'], 'size' => $page['size']),
                'createtime desc',
                '',
                'id,uid,name,createtime,updatetime,synopsis,img_id,type',$group));

            //下面这一块主要是取出各项数据组装
            foreach ($res['info']['list'] as $vo) {
                $imgcondition['id']                = $vo['img_id'];
                $img                               = apiCall(UserPictureApi::GET_INFO, array($imgcondition));
                $groupcondition['p_id']        = $vo['id'];
                $productgroup                        = apiCall(ProductGroupApi::GET_INFO, array($groupcondition));
                $attendsum                        = apiCall(GroupattendApi::GET_COUNT, array($groupcondition));
                $productimglist[$vo['id']]['id']   = $vo['id'];
                $productimglist[$vo['id']]['name'] = $vo['name'];

                //计算发布多久了
                $lasttime = date('U') - $vo['createtime'];
                if ($lasttime < 3600 * 24) {
                    if (round($lasttime / 3600) == 0) {
                        $lasttime = round($lasttime / 60) . '分钟前';
                    } else {
                        $lasttime = round($lasttime / 3600) . '小时前';
                    }
                } else {
                    $lasttime = round($lasttime / (3600 * 24)) . '天前';
                }
                $productimglist[$vo['id']]['lasttime'] = $lasttime;
                $productimglist[$vo['id']]['synopsis'] = mb_substr($vo['synopsis'], 0, 60, 'utf-8') . '...';



                $productimglist[$vo['id']]['imglist'] = $img['info']['id'];


                $productimglist[$vo['id']]['price']     = $productgroup['info']['price'];
                $productimglist[$vo['id']]['ori_price'] = $productgroup['info']['ori_price'];
                $productimglist[$vo['id']]['quantity']  = $productgroup['info']['quantity'];//库存

                //将商品拼团的信息查出放入数组
                $productimglist[$vo['id']]['start_time']   = $productgroup['info']['start_time'];
                $productimglist[$vo['id']]['end_time']   = $productgroup['info']['end_time'];
                $productimglist[$vo['id']]['group_sum']   = $productgroup['info']['group_sum'];
                //将参团的信息查出放入数组
                $productimglist[$vo['id']]['attend_sum']   = $attendsum['info'];

            }



            //下面第一种情况用于AJAX异步请求
            if ($page['curpage'] > 1) {
                $strinfo = '';
                foreach ($productimglist as $product) {
                    $strinfo = $strinfo . "<div class='good-content'>
                                   <div class='good-top'>
                                     <div class='good-userimg'><img src=" . $product['avatar'] . " width='50px' height='50px'></div>
                                     <div class='good-name'><span class='good-sname'>" . $product['nickname'] . "</span><br/><span class='good-time'>" . $product['lasttime'] . "</span></div>
                                     <div class='good-price'><i class='fa fa-jpy'></i><span>" . $product['price'] . "</span></div>" . "
                                     </div>
                                     <a class='good-main' href=" . U('index/good_detail', array('id' => $product['id'])) . ">
                            <div class='good-mtop'>" . $product['name'] . "</div>
                            <div class='good-intr'><p>" . $product['synopsis'] . "</div>
                            <div class='good-img'>";
                    $imgstr  = '';
                    foreach ($product['imglist'] as $imglist) {
                        if (!empty($imglist['path'])) {
                            $imgstr = $imgstr . "<div class='good-img-list'><img src=" . "http://muyin.8raw.com/api.php/picture/index?id=" . $imglist['id'] . "&size=160" . "></div>";
                        }
                    }
                    $strinfo = $strinfo . $imgstr . "</div>
                        </a>
                    </div>";
                }
                echo $strinfo;
            } else {
                //首页第一页输出
                //调出首页顶部的幻灯片
                $banners = $this->select_slide(1);
                $this->assign('banners', $banners);//幻灯片赋值
              //dump($productimglist);exit;
                $this->assign('product', $productimglist);

                $this->display();
            }
        } else {
            if ($page['curpage'] > 1) {
                echo false;//防止ajax请求的报错
            } else {
//                $banners = $this->select_slide(1);
//                $this->assign('banners', $banners);//幻灯片赋值
                $this->display();
            }
        }

    }

    /*
        * 宝贝详情
        * */
    //这里可以和上面的一起封装一个函数
    public function good_index(){
        $product['id'] = I('id');
        $res = apiCall(ProductApi::ALLQUERY, array($product,'','','','id,uid,name,createtime,synopsis,dt_origin_country,postage,img_id,detail,type',false));
        foreach($res['info']['list'] as $k=>$vo){
            $imgcondition['id'] = $vo['img_id'];
            $img = apiCall(UserPictureApi::GET_INFO, array($imgcondition));
            $groupcondition['p_id']        = $vo['id'];
            $productgroup                        = apiCall(ProductGroupApi::GET_INFO, array($groupcondition));
            $attendsum                        = apiCall(GroupattendApi::GET_COUNT, array($groupcondition));
            $groupconfig                       = apiCall(GroupOrderApi::QUERY_NO_PAGING, array($groupcondition));

            foreach($groupconfig['info'] as $k =>$v){
                $wei_yi_map['productid']=$vo['id'];
                $wei_yi_map['type']=$v['type'];
                $wei_yi=apiCall(GroupApi::GET_INFO,array($wei_yi_map));

                if(empty($wei_yi['info'])){

                    $groupconfig['info'][$k]['status']=0;
                }elseif(!empty($wei_yi['info']['status'])){

                    $groupconfig['info'][$k]['status']=$wei_yi['info']['status'];
                }

            }
            $map=[];$map['productid']=$vo['id'];$map['gm.status']=1;
            $weigroup                        = apiCall(GroupApi::WEI, array($map));
            $map=[];$map['productid']=$vo['id'];$map['gm.status']=2;
            $chenggroup                        = apiCall(GroupApi::WEI, array($map));
            $productimglist[$vo['id']]['id']   = $vo['id'];
            $productimglist[$vo['id']]['name'] = $vo['name'];
            //计算发布多久了
            $lasttime = time() - $vo['createtime'];
            if ($lasttime < 3600 * 24) {
                if(round($lasttime / 3600) == 0){
                    $lasttime = round($lasttime / 60) . '分钟前';
                }else{
                    $lasttime = round($lasttime / 3600) . '小时前';
                }
            } else {
                $lasttime = round($lasttime / (3600 * 24)) . '天前';
            }
            $productimglist[$vo['id']]['lasttime'] = $lasttime;
            $productimglist[$vo['id']]['synopsis'] = $vo['synopsis'];//介绍
            $productimglist[$vo['id']]['dt_origin_country'] = $vo['dt_origin_country'];//货源
            $productimglist[$vo['id']]['postage'] = $vo['postage'];//邮费
            if(count($productimglist[$vo['id']]['imglist']) < 6){
                $productimglist[$vo['id']]['imglist']['0'] = $img['info'];//需要判断图片是不是大于6张了
            }
            $productimglist[$vo['id']]['price'] = $productgroup['info']['price'];

            $productimglist[$vo['id']]['ori_price'] = $productgroup['info']['ori_price'];
            $productimglist[$vo['id']]['quantity']  = $productgroup['info']['quantity'];//库存
            if($productimglist[$vo['id']]['quantity']<1) $this->error('商品已被抢光','http://muyin.8raw.com/index.php/Home/group/index');
            //将商品拼团的信息查出放入数组
            $productimglist[$vo['id']]['start_time']   = date('m月d日h时i分',$productgroup['info']['start_time']);
            $productimglist[$vo['id']]['end_time']   = date('m月d日H时i分',$productgroup['info']['end_time']);

            $productimglist[$vo['id']]['group_sum']   = $productgroup['info']['group_sum'];
            $productimglist[$vo['id']]['group_config']   = $groupconfig['info'];


            //将参团的信息查出放入数组
            $productimglist[$vo['id']]['attend_sum']   = $attendsum['info'];
            //将拼团的信息查出放入数组
            $productimglist[$vo['id']]['wei_group']   = $weigroup['info'];
            $productimglist[$vo['id']]['cheng_group']   = $chenggroup['info'];
            $productimglist[$vo['id']]['detail']   = $this->tihuan($vo['detail']);
        }
        //require_once('\Home\Controller\JssdkController.class.php');
        //$jssdk=new jssdkController("wx5e6da06a44a9c39e", "acae303b8ec06f9592ee3cf2844b2ec3");
        $jssdk =new \Common\Api\WeixinApi("wx5e6da06a44a9c39e", "acae303b8ec06f9592ee3cf2844b2ec3");
        //$this->wxapi = new WeixinApi($this->wxaccount['appid'], $this->wxaccount['appsecret']);
        $jssdk =$this->wxapi;
        $signPackage = $jssdk->GetSignPackage();
        $this->assign('signPackage',$signPackage);
        //购买商品的用户id
        $this->assign($productimglist[$vo['id']]);

        $this->assign('buyuid',$this->userinfo['uid']);
        $this->display();
    }

    /*
    * 宝贝详情
    * */
    //这里可以和上面的一起封装一个函数
    public function good_detail(){
        $product['id'] = I('id');
        $group_status=I('status');
        //if(!empty($group_status)) session('group_status',$group_status);
        $counttype=I('counttype');
        $this->assign('counttype',$counttype);
        $res = apiCall(ProductApi::ALLQUERY, array($product,'','','','id,uid,name,createtime,synopsis,dt_origin_country,postage,img_id,detail,type',false));
        foreach($res['info']['list'] as $k=>$vo){
            $imgcondition['id'] = $vo['img_id'];
            $img = apiCall(UserPictureApi::GET_INFO, array($imgcondition));

            $groupcondition['p_id']        = $vo['id'];
            $productgroup                        = apiCall(ProductGroupApi::GET_INFO, array($groupcondition));
            $pricesum['p_id']        = $vo['id'];$pricesum['type']        = $counttype;
            $price_sum                        = apiCall(GroupOrderApi::GET_INFO, array($pricesum));

            $map=[];$map['productid']=$vo['id'];$map['gm.status']=1;$map['type']=$counttype;
            $weigroup                        = apiCall(GroupApi::WEI, array($map));
            $map=[];$map['productid']=$vo['id'];$map['gm.status']=2;$map['type']=$counttype;
            $chenggroup                        = apiCall(GroupApi::WEI, array($map));

            if(!empty($weigroup['info']['list'])){
                $people['ga.groupid']=$weigroup['info']['list']['0']['id'];
                $group_people=apiCall(GroupattendApi::PEOPLE_ATTEND,array($people));

                $group_condition['groupid']=$weigroup['info']['list']['0']['id'];
                $attendsum                        = apiCall(GroupattendApi::GET_COUNT, array($group_condition));

            }else{
                $people['ga.groupid']=$chenggroup['info']['list']['0']['id'];
                $group_people=apiCall(GroupattendApi::PEOPLE_ATTEND,array($people));

                $group_condition['groupid']=$chenggroup['info']['list']['0']['id'];
                $attendsum                        = apiCall(GroupattendApi::GET_COUNT, array($group_condition));

            }






            $productimglist[$vo['id']]['id']   = $vo['id'];
            $productimglist[$vo['id']]['name'] = $vo['name'];
            //计算发布多久了
            $lasttime = time() - $vo['createtime'];
            if ($lasttime < 3600 * 24) {
                if(round($lasttime / 3600) == 0){
                    $lasttime = round($lasttime / 60) . '分钟前';
                }else{
                    $lasttime = round($lasttime / 3600) . '小时前';
                }
            } else {
                $lasttime = round($lasttime / (3600 * 24)) . '天前';
            }
            $productimglist[$vo['id']]['lasttime'] = $lasttime;
            $productimglist[$vo['id']]['synopsis'] = $vo['synopsis'];//介绍
            $productimglist[$vo['id']]['dt_origin_country'] = $vo['dt_origin_country'];//货源
            $productimglist[$vo['id']]['postage'] = $vo['postage'];//邮费
            if(count($productimglist[$vo['id']]['imglist']) < 6){
                $productimglist[$vo['id']]['imglist'][$k] = $img['info'];//需要判断图片是不是大于6张了
            }

            $productimglist[$vo['id']]['ori_price'] = $productgroup['info']['ori_price'];
            $productimglist[$vo['id']]['quantity']  = $productgroup['info']['quantity'];//库存
            if($productimglist[$vo['id']]['quantity']<1) $this->error('商品已被抢光','http://muyin.8raw.com/index.php/Home/group/index');
            //将商品拼团的信息查出放入数组
            $productimglist[$vo['id']]['start_time']   = date('m月d日h时i分',$productgroup['info']['start_time']);
            $productimglist[$vo['id']]['end_time']   = date('m月d日H时i分',$productgroup['info']['end_time']);


            $productimglist[$vo['id']]['price'] = $price_sum['info']['price'];
            $productimglist[$vo['id']]['group_sum']   = $price_sum['info']['sum'];


            //将参团的信息查出放入数组
            $productimglist[$vo['id']]['attend_sum']   = $attendsum['info'];
            //将拼团的信息查出放入数组
            $productimglist[$vo['id']]['wei_group']   = $weigroup['info'];
            if(!empty($group_people['info'])) $productimglist[$vo['id']]['group_people']   = $group_people['info'];

            $productimglist[$vo['id']]['detail']   = $this->tihuan($vo['detail']);
        }
        //require_once('\Home\Controller\JssdkController.class.php');
       //$jssdk=new jssdkController("wx5e6da06a44a9c39e", "acae303b8ec06f9592ee3cf2844b2ec3");
        $jssdk =new \Common\Api\WeixinApi("wx5e6da06a44a9c39e", "acae303b8ec06f9592ee3cf2844b2ec3");
        //$this->wxapi = new WeixinApi($this->wxaccount['appid'], $this->wxaccount['appsecret']);
        $jssdk =$this->wxapi;
        $signPackage = $jssdk->GetSignPackage();
        $this->assign('signPackage',$signPackage);
        //购买商品的用户id


        $this->assign('group_status',$group_status);

        $this->assign('num',$price_sum['info']['sum']-$attendsum['info']);
        $this->assign($productimglist[$vo['id']]);
        $this->assign('buyuid',$this->userinfo['uid']);
        $this->display();
    }

    public function tihuan($url){

        $url=str_replace('&lt;','<',$url);
        $url=str_replace('&gt;','>',$url);
        $url=str_replace('&quot;','"',$url);

return $url;

//        &lt;p&gt;**************************************************&lt;/p&gt;&lt;p&gt;&lt;img src=&quot;
//        http://muyin.8raw.com/Uploads/ueditor/upload/image/20161212/1481535283190412.jpg&quot; alt=&quot;1481535283190412.jpg
//        //&quot;/&gt;&lt;/p&gt;&lt;p&gt;&lt;br/&gt;&lt;/p&gt;

    }

    public function status($pid){
        $map['productid']=$pid;$map['status']=1;
        $result=apiCall(GroupApi::GET_INFO,array($map));

        if(!empty($result['info'])) {
            $resu='tuanyuan';
            $groupid=$result['info']['id'];

        }else{
            $resu='tuanzhang';
        }

        return(array('type'=>$resu,'groupid'=>$groupid));
    }


public function test(){
    $root=__ROOT__.'/public';
    var_dump($root);
}



    /*
     * 购买商品
     * */
    public function buy_good(){
        $counttype=I('counttype');

        if($counttype=='0'){

        }else{
            if(empty($counttype)) $counttype=session('counttype');
        };

        session('counttype',$counttype);

        $pid=I('id')?I('id'):session('pid');
        $uid=I('uid') ? I('uid') : session('uid');
        //$type=I('type')?I('type'):session('type');

        session('pid',$pid);
        session('uid',$uid);


        //判断为团员还是团长
        $co['productid']=$pid;$co['type']=$counttype;
        $group_zhang=apiCall(GroupApi::GET_INFO,array($co));

        if(!empty($group_zhang['info'])){
            if($group_zhang['info']['status']!=='1'){
                $this->error('此团状态不可参加','http://muyin.8raw.com/index.php/Home/group/index');
            }
            $type='tuanyuan';
            $groupid=$group_zhang['info']['id'];
        }elseif(empty($group_zhang['info'])){
            $type='tuanzhang';
        }


        if($type == 'tuanzhang'){
            $map['productid']=$pid;
            $map['uid']=$uid;
            $group=apiCall(GroupApi::GET_INFO,array($map));
            if(!empty($group['info'])) $this->error("不能重复拼团");
            $ma['uid']=$uid;$ma['p_id']=$pid;
            $groupattend=apiCall(GroupattendApi::GET_INFO,array($ma));
            if(!empty($groupattend['info'])) $this->error("不能参加同一个团");
            $con['productid']=$pid;$con['type']=$counttype;
            $group_zhang=apiCall(GroupApi::GET_INFO,array($con));
            if(!empty($group_zhang['info'])) $this->error("此团已有团长");

        }elseif($type == 'tuanyuan'){
            session('groupid',$groupid);//拼团id
            $map['id']=$groupid;
            $group=apiCall(GroupApi::GET_INFO,array($map));

            if(!$group['status']||empty($group['info'])) $this->error("拼团错误");
            if($group['info']['group_sum']<=$group['info']['group_count']) $this->error('人数已满');
            if($group['info']['uid']==$uid) $this->error("团长不能参加自己的团");
            $ma['uid']=$uid;$ma['p_id']=$pid;
            $groupattend=apiCall(GroupattendApi::GET_INFO,array($ma));
            if(!empty($groupattend['info'])) $this->error("不能参加同一个商品团购");

        }

        session('type',$type);//拼团类型var
        session('groupid',$groupid);//拼团类型var

        $wxusermap['uid'] = I('uid') ? I('uid') : session('uid');
        $wxusergroup['gid']=I('gid') ? I('gid') : Null;
        //判断是否有可供选择的地址没有就需要新建
        $hasaddrres = apiCall(AddressApi::COUNT , array($wxusermap));
        if($hasaddrres['status']){
            $this->assign('addrecount',$hasaddrres['info']);
        }
        //判断是否进行地址选择如果选择了就用选择的
        if(!empty(I('addressid'))){
            $addressmap['id'] = I('addressid');
            session('addressid',$addressmap['id']);//为的是在生成订单时获得相应的地址信息的方便
            $selectres = apiCall(AddressApi::GET_INFO , array($addressmap));
            if($selectres['status']){
                $this->assign($selectres['info']);
            }
        }else{
            //如果没有则将调用默认地址
            $addressdefaultmap['itboye_address.uid'] = $wxusermap['uid'];
            $res = apiCall(WxuserApi::FIND_DEFAULT_ADDRESS , array($addressdefaultmap));//联合查询查出默认地址
            if($res['status']){
                session('addressid',$res['info']['id']);
                $this->assign($res['info']);
            }
        }


        //调出商品信息
        $product['id'] = I('id') ? I('id') : session('id');//商品id
        session('id',$product['id']);//存入商品ID
        session('uid',$wxusermap['uid']);//存入购买者用户
        $res = apiCall(ProductApi::ALLQUERY, array($product,'','','','id,uid,name,synopsis,postage,img_id,type',true));
        foreach($res['info']['list'] as $vo){
            $imgcondition['id'] = $vo['img_id'];
            $img = apiCall(UserPictureApi::GET_INFO, array($imgcondition));
            $groupcondition['p_id'] = $vo['id'];
            $productgroup = apiCall(ProductGroupApi::GET_INFO, array($groupcondition));
            $productimglist[$vo['id']]['id'] = $vo['id'];//商品id
            $productimglist[$vo['id']]['name'] = $vo['name'];
            $productimglist[$vo['id']]['synopsis'] = $vo['synopsis'];//介绍
            $productimglist[$vo['id']]['postage'] = $vo['postage'];//邮费
            $con['p_id']=$pid;$con['type']=$counttype;
            $config=apiCall(GroupOrderApi::GET_INFO,array($con));
            $productimglist[$vo['id']]['price'] = $config['info']['price'];

            $productimglist[$vo['id']]['ori_price'] = $productgroup['info']['ori_price'];
            $productimglist[$vo['id']]['number'] = $productgroup['info']['quantity'];//商品库存
            $productimglist[$vo['id']]['imglist'] = $img['info']['id'];
        }

        $this->assign('group_id',$groupid);
        $this->assign('type',$type);
        $this->assign('groupid',$groupid);
        $this->assign('counttype',$counttype);

        $this->assign($productimglist[$product['id']]);
        $this->display();
    }

    /*
     * 订单信息的生成
     * */
    public function produce_order(){
        //获取拼团类型，并验证是否可以购买
        $type=I('type');
        $counttype=I('counttype');

        if($type=='tuanyuan'){
        $groupid=I('group_id');
        $map['id']=$groupid;
        $group=apiCall(GroupApi::GET_INFO,array($map));
        if(!$group['status']||empty($group['info'])) $this->error("拼团错误");
        if($group['info']['group_sum']<=$group['info']['group_count']) $this->error('人数已满');

        }
        if(empty(I('addressid'))&&empty(session('addressid'))) $this->error("没有填写地址");
        if(IS_POST){
            $model = M();
            $model -> startTrans();//开启事务
            $flag = false;
            session('addressid', I('addressid') ? I('addressid') : session('addressid'));//存入送货地址
            $productmap['id'] = session('id');
            $pid=session('id');
            $productgroupmap['p_id'] = $productmap['id'];
            $buy_number = 1;//购买商品的数量
            $productinfo = apiCall(ProductApi::GET_INFO,array($productmap));//运用session将商品基本的信息查询出来
            $productgroupinfo = apiCall(ProductgroupApi::GET_INFO, array($productgroupmap));//运用session将拼团特殊信息的价格信息查询出来
            //下面要做一个判断防止返回时有重复提交订单  导致有多个订单存在
            $fla=true;
            $uid=session("global_user");
            if(empty($uid)) $this->error("查不到用户信息");
            $vii['o.uid']=$uid['id'];$vii['item.p_id']=$productmap['id'];$vii['o.pay_status']=0;
            $vi=apiCall(OrdersApi::QUERY_VII,array($vii));
            if(!empty($vi['info'])) $fla=false;

            $map['uid']=session('uid');$map['p_id']=$productmap['id'];
            $copy=apiCall(GroupattendApi::GET_INFO,array($map));
            if($type=='tuanzhang'){
                $grouptype=1;
            }
            if($type=='tuanyuan'){
                $grouptype=$groupid;}
            if($productinfo['info']['status'] == 1 && $productgroupinfo['info']['quantity'] >= $buy_number&&$fla) {
                //生成order表的数据存入
                $entity['uid'] = session('uid');//用户的ID
                $con['p_id']=$pid;;$con['type']=$counttype;
                $config=apiCall(GroupOrderApi::GET_INFO,array($con));
                $entity['price'] = $config['info']['price']*$buy_number;
                $entity['order_code'] = getOrderid($entity['uid']);//获得订单编号
                $entity['ori_price'] = $productgroupinfo['info']['ori_price'];
                $entity['post_price'] = $productinfo['info']['postage'];//邮费
                $entity['status'] = 1;
                $entity['pay_status'] = 0;
                $entity['order_status'] = 2;
                $entity['cs_status'] = 0;
                $entity['createtime'] = time();
                $entity['updatetime'] = time();
                $entity['grouptype']=$grouptype;
                $entity['counttype']=$counttype;
                $orderinfo = apiCall(OrdersApi::ADD, array($entity));
                if (!$orderinfo['status']) {
                    $flag = true;
                }
         //找到一张图片作为主图放入到item当中作为商品的头像
                $imgidmap['pid'] = $productmap['id'];
                $imgidinfo = apiCall(ProductImageApi::GET_INFO, array($imgidmap));
                if (!$imgidinfo['status']) {
                    $flag = true;
                }
                $imgmap['id'] = $imgidinfo['info']['img_id'];
                $imginfo = apiCall(UserPictureApi::GET_INFO, array($imgmap));
                if (!$imginfo['status']) {
                    $flag = true;
                }
                //订单编号的生成并item和order表相关联
                $item['img'] = $imginfo['info']['path'];
                $item['name'] = $productinfo['info']['name'];
                //获取拼团价格
                $con['p_id']=$pid;$con['type']=$counttype;
                $config=apiCall(GroupOrderApi::GET_INFO,array($con));
                $item['price'] = $config['info']['price'];
                $item['ori_price'] = $productgroupinfo['info']['ori_price'];
                $item['post_price'] = $productinfo['info']['postage'];
                $item['count'] = $buy_number;
                $item['order_code'] = $entity['order_code'];//获得订单编号
                $item['createtime'] = time();
                $item['p_id'] = $productmap['id'];
                $item['dt_origin_country'] = $productinfo['info']['dt_origin_country'];
                $orderiteminfo = apiCall(OrdersItemApi::ADD, array($item));
                if (!$orderiteminfo['status']) {
                    $flag = true;
                }
                //生成送货地址存入与货物相关联
                $addressmap['id'] = session('addressid');//获得送货地址ID
                $addressinfo = apiCall(AddressApi::GET_INFO, array($addressmap));
                $contactinfo['contactname'] = $addressinfo['info']['contactname'];
                $contactinfo['uid'] = $entity['uid'];
                $contactinfo['province'] = $addressinfo['info']['province'];
                $contactinfo['detailinfo'] = $addressinfo['info']['detailinfo'];
                $contactinfo['area'] = $addressinfo['info']['area'];
                $contactinfo['mobile'] = $addressinfo['info']['mobile'];
                $contactinfo['order_code'] = $item['order_code'];
                $contactinfo['city'] = $addressinfo['info']['city'];
                $contactres = apiCall(OrdersContactInfoApi::ADD, array($contactinfo));
                if (!$contactres['status']) {
                    $flag = true;
                }
                //减少操作
                $productgroup['quantity'] = $productgroupinfo['info']['quantity']-$buy_number;
                $productgroupres = apiCall(ProductGroupApi::SAVE,array($productgroupmap,$productgroup));
                if(!$productgroupres['status']){
                    $flag = true;
                }
                if($productgroup['quantity'] <= 0){
                    //如果库存数量等于0 product表中的status设置为0
                    $addstatus['status'] = 0;
                    $setproductres = apiCall(ProductApi::SAVE, array($productmap, $addstatus));//运用session将相应的信息查询出来
                    if (!$setproductres['status']) {
                        $flag = true;
                    }
                }
                //grouporderid
                if($type=='tuanyuan'){
                    $order_code=$item['order_code'];
                    $uid=session('uid');
                    $groupid=session('groupid');
                    $entity=[];$entity['ordercode']=$order_code;$entity['uid']=$uid;$entity['groupid']=$groupid;
                    $add=apiCall(GrouporderidApi::ADD,array($entity));
                    }
                //最后检测一次团的团员情况
                if($type=='tuanyuan'){
                    $groupid=session('groupid');
                    $map=[];$map['id']=$groupid;
                    $add=apiCall(GroupApi::GET_INFO,array($map));
                    if($add['info']['group_sum']<=$add['info']['gorup_count']) $this->error("团员已满无法加入");
                }
                if ($flag) {
                    $model->rollback();
                    $this->error('订单发送失败');
                } else {
                    $model->commit();

                    $this->success('订单生成成功', 'http://muyin.8raw.com/index.php/Home/Pay/jsapi/?' . 'order_code=' . $item['order_code'].'&'.'type='.$type.'&groupid='.$groupid.'&counttype='.$counttype.'&pid='.$pid);
                    //$this->success('订单生成成功', 'http://muyin.8raw.com/index.php/Home/PAYTest/ajaxinformzhang/?' . 'order_code=' . $item['order_code']);
                }
            }else{
                $this->error('您已有一个订单，请先完成','http://muyin.8raw.com/index.php/Home/Mybuysell/mybuy.htm');
            }
        }else{
            $this->error('大兄弟你来错地方了');
        }


    }

    /*
     *选择地址
     * */
    public function select_address(){
        $map = array('openid' => $this -> openid, 'wxaccount_id' => $this -> wxaccount['id']);//wxaccount_id表示所属的微信公众账号
        $user = apiCall(WxuserApi::GET_INFO , array($map));
        $this->assign('d_addr',$user['info']['default_address']);
        $map = array('uid'=>$user['info']['id']);
        $result = apiCall(AddressApi::QUERY_NO_PAGING , array($map));
        $this->assign("addr",$result['info']);
        $this->display();
    }

    /*
     * 支付
     * */
    public function pay_money(){
        $this->display();
    }



    /*
     * 支付完成，团长成团
     * */
    public function beinggroup($order_code =0){
        //根据支付编号查出商品和购买者信息
        $map['order_code']=$order_code;

        //查出商品id
        $itemdata=apiCall(OrdersItemApi::GET_INFO,array($map));
        $orderdata=apiCall(OrdersApi::GET_INFO,array($map));
        if(!$itemdata['status']||!$orderdata['status']) exit("拼团失败，请联系客服！");
        if(empty($itemdata['info'])||empty($orderdata['info'])) exit("找不到您的支付订单，请联系客服！");
        $data=$itemdata['info'];
        $pid=$data['p_id'];
        $groupmap['pid']=$pid;
        $uid=$orderdata['info']['uid'];
        //查出商品信息
        $group=apiCall(ProductGroupApi::GET_INFO,array($groupmap));
        if(!$group['status']) exit("建团失败，请联系客服！");
        if(empty($group['info'])) exit("找不到您的支付订单，请联系客服！");
        $sum=$group['info']['group_sum'];
        $entity=['group_sum'=>$sum,'productid'=>$pid,'group_count'=>1,'createtime'=>time(),'status'=>1,'uid'=>$uid];

        $add=apiCall(GroupApi::ADD,array($entity));
        if(!$add['status']||empty($add['status'])) exit("错误");
        //调用参团（团长）
        $groupid=$add['info'];
        $uid=$orderdata['info']['uid'];
        $attend=array('groupid'=>$groupid,'uid'=>$uid,'status'=>1,'p_id'=>$pid);

        $groupattend=$this->ingroup($attend);

        if($add['status']&&!empty($add['info'])&&$groupattend) {
            return("团拼成功");
        }else{
            return("团拼失败");
        }

    }

    public function ingroup($entity,$type=0){
        //团长

            $add=apiCall(GroupattendApi::ADD,array($entity));
            if(!$add['status']||empty($add['info'])) $this->error("加入团错误");
            return true;

    }


    public function yuaningroup($order_code =0,$groupid=0){
        $map['order_code']=$order_code;
        $groupid=session('groupid');
        //查出商品id
        $itemdata=apiCall(OrdersItemApi::GET_INFO,array($map));
        $orderdata=apiCall(OrdersApi::GET_INFO,array($map));
        if(!$itemdata['status']||!$orderdata['status']) exit("拼团失败，请联系客服！");
        if(empty($itemdata['info'])||empty($orderdata['info'])) exit("找不到您的支付订单，请联系客服！");
        $data=$itemdata['info'];
        $pid=$data['p_id'];
        //调用参团（团员）
        $uid=$orderdata['info']['uid'];
        $attend=array('groupid'=>$groupid,'uid'=>$uid,'status'=>2,'p_id'=>$pid);
        $add=apiCall(GroupattendApi::ADD,array($attend));
        if(!$add['status']||empty($add['info'])) $this->error("加入团错误");

        //更新团的参加人数
        $map=[];$map['groupid']=$groupid;
        $count=apiCall(GroupattendApi::GET_COUNT,array($map));
        $id['id']=$groupid;$entity=[];$entity['group_count']=$count['info'];
        $gengxin=apiCall(GroupApi::SAVE,array($id,$entity));
        if(!$gengxin['status']||empty($gengxin['info'])) $this->error("加入团错误");

        return("参团成功");


    }



/*
    public function mygroup(){
        $ordermap['a.uid'] = $this->userinfo['uid'];
        $map['uid']=$this->userinfo['uid'];
        $mygroup=apiCall(GroupattendApi::QUERY_NO_PAGING,array($map));
         $productidarr = array_column($mygroup['info'], 'ordercode');
        $productidstr = implode(',', $productidarr);
        $pimap['o.order_code']  = array('in', $productidstr);
        $buyinfo = apiCall(OrdersApi::SELECT_SELL_ORDER,array($pimap,'i.name,i.img,i.price,o.pay_status,o.order_status,o.uid,o.order_code'));

        if($buyinfo['status']){
            if(!is_null($buyinfo['info'])) {
                //将所有订单编号拿出来
                foreach ($buyinfo['info'] as $vo) {
                    $order_code[] = $vo['order_code'];
                }
                $order_code_str = implode(',', $order_code);
                //进行物流单号查询
                $order_codemap['order_code'] = array('in', $order_code_str);
                $orderinfo = apiCall(OrdersExpressApi::QUERY_NO_PAGING, array($order_codemap));
                if ($orderinfo['status']) {
                    $this->assign('orderinfo', $orderinfo['info']);
                    $this->assign('buyinfo', $buyinfo['info']);
                    $this->display();
                } else {
                    $this->error('对不住 物流单号查询失败');
                }
            }else{
                $this->display();
            }
        }else{
            $this->error('抱歉出错了');
        }
    }

*/

    public function mygrouplist(){

        $map = array('openid' => $this -> openid, 'wxaccount_id' => $this -> wxaccount['id']);//wxaccount_id表示所属的微信公众账号
        $result = apiCall(WxuserApi::GET_INFO , array($map));
        $this->assign($result['info']);
        $this->display();


    }



    public function mygroup(){

        $status=I('status','0');

        $map['ga.uid']=$this->userinfo['uid'];
        if($status==1) ;
        if($status==2) $map['g.status']=1;
        if($status==3) $map['g.status']=2;
        if($status==4) $map['g.status']=-1;


        if(empty($map)) $this->error('查询信息错误');
        $group=apiCall(GroupattendApi::QUERY_GROUP,array($map));


        $this->assign('buyinfo',$group);
        return $this->display();


    }



    public function groupdetail(){



        $id=I('id','0');

        $group=apiCall(GroupattendApi::QUERY_GROUPDETAIL,array($id));
        $attend=$group['query'];
        $num=$attend['group_sum']-$attend['group_count'];
        $deadtime=$attend['end_time'];
        $nowtime=time();
        $time=true;


        if($deadtime<$nowtime) $time=false;
        $remainder=($deadtime-$nowtime);
        $remainder=$this->Sec2Time($remainder);



        $this->assign('num',$num);
        $this->assign('time',$remainder);
        $this->assign('people',$group['people']);
        $this->assign('buy',$group['query']);
        return $this->display();


    }



    public function callfriends() {
        http://muyin.8raw.com/index.php/Home/group/good_detail/id/2469.htm
    }

    function Sec2Time($time){
        if(is_numeric($time)){
            $value = array(
                "years" => 0, "days" => 0, "hours" => 0,
                "minutes" => 0, "seconds" => 0,
            );
            if($time >= 31556926){
                $value["years"] = floor($time/31556926);
                $time = ($time%31556926);
            }
            if($time >= 86400){
                $value["days"] = floor($time/86400);
                $time = ($time%86400);
            }
            if($time >= 3600){
                $value["hours"] = floor($time/3600);
                $time = ($time%3600);
            }
            if($time >= 60){
                $value["minutes"] = floor($time/60);
                $time = ($time%60);
            }
            $value["seconds"] = floor($time);
            //return (array) $value;
            $t=$value["days"] ."天"." ". $value["hours"] ."小时". $value["minutes"] ."分".$value["seconds"]."秒";
            Return $t;

        }else{
            return (bool) FALSE;
        }
    }





    /*
     * 幻灯片的读取
     *
     * */
    public function select_slide($position){
        $bannermap['position'] = $position;
        $bannersres = apiCall(BannersApi::ACCORD_BANNERS, array($bannermap,'','sort'));
        //首页幻灯片的判断
        if($bannersres['status']){
            $banners = array();
            foreach($bannersres['info'] as $vo){
                if(count($banners) < 3){
                    $banners[] = $vo;
                }
            }
        }else{
            $this->error('首页幻灯片读取失败 抱歉');
        }
        return $banners;

    }




    /*
     * 提示
     *
     * */
    public function message(){
        $this->success('亲点击上面的团购按钮，参加拼团','',1);

    }
}



